package com.whjfxx.terminal.controller;

import com.alibaba.fastjson.JSONObject;
import com.whjfxx.terminal.api.param.ActiveParam;
import com.whjfxx.terminal.api.param.ApiBaseParam;
import com.whjfxx.terminal.api.server.ActivateService;
import com.whjfxx.terminal.api.valid.ActivateValid;
import com.whjfxx.terminal.api.vo.ActivateVo;
import com.whjfxx.terminal.commons.ApiDecodeUtil;
import com.whjfxx.terminal.commons.Base64Util;
import com.whjfxx.terminal.commons.Result;
import com.whjfxx.terminal.utils.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by b.c on 2022/1/18 9:29
 */
@Slf4j
@RestController
@RequestMapping("terminal/v100")
@DependsOn
public class TerminalActivateApi {

    @Autowired
    ActivateService activateService;



    @PostMapping("activate")
    public Result<Object> activate(@RequestBody @Validated ApiBaseParam param) {
        System.out.println("param: " + JSONObject.toJSONString(param));
        ActiveParam activeParam = ApiDecodeUtil.encodeTeBean(param.getBody(), ActiveParam.class);

        System.out.println(JSONObject.toJSONString(activeParam));
        // 参数校验
        ActivateValid.valid(activeParam);

        // 获取token  todo 默认token = bf58c457a72244cda9ae79436b3f9d63
//        String func_token = "bf58c457a72244cda9ae79436b3f9d63";

        String func_token = activateService.getToken(activeParam.getApp_name(), activeParam.getFunc_name());
        // 签名验证
        SignUtil.validSign(activeParam, func_token);
        // 激活处理
        ActivateVo activateVo = activateService.activate(activeParam);
        String key_sign = SignUtil.sign(activateVo, func_token);
        activateVo.setKey_sign(key_sign);
        String base64 = Base64Util.encodeToString(JSONObject.toJSONString(activateVo));
        return Result.success(base64);
    }


    public static void main(String[] args) {

        System.out.println(Base64Util.decodeToString("eyJmdW5jX25hbWUiOiLor7vljaHlupMiLCJhcHBfdmVyIjoiMS4wLjAxIiwidmVyc2lvbiI6IjEwMCIsInJlcV90aW1lIjoiMjAyMjA2MjUxNjAxMzMiLCJ0ZXJtaW5hbF90eXBlIjoiQVBPUyBBOCIsImtleV9zaWduIjoiMDY2RDFCQkMwQjFGOTUzMTNBQjZEREY1OTBGMDRGQ0IiLCJ0ZXJtaW5hbF9zbiI6IjE4MTJDQTgwMTkzNiIsImFwcF9uYW1lIjoi5Yy755aX57O757ufIiwidGVybWluYWxfbG9jYWwiOnsibG9uIjoiMTEzLjYxOTU1OCIsImxhdCI6IjI4LjM2MjIwNSJ9fQ=="));
    }
}
